<?php
declare (strict_types = 1);
/**
 * Redis
 */
namespace app\common\extend;

use think\facade\Cache;

class Redis
{

    protected $redis;
    protected $prefix;

    public function __construct()
    {
        $this->redis  = Cache::store('redis')->handler();
        $this->prefix = env('redis.prefix');
    }

    /**
     * 设置缓存（哈希）
     */
    public function hMSet($name = '', $value, $config = [])
    {

        $name = self::name($name);

        $set = $this->redis->hMSet($name, $value);

        if ($set != true) exception();

        if (isset($config['expire'])) $this->expire($name, $config['expire']);

        return true;
    }

    /**
     * 设置缓存（哈希）
     */
    public function hSet($name = '', $key, $value, $config = [])
    {

        $name = self::name($name);

        if (is_array($value)) $value = json_encode($value, JSON_UNESCAPED_UNICODE);

        $set = $this->redis->hSet($name, $key, $value);

        if ($set !== 1) exception();

        if (isset($config['expire'])) $this->expire($name, $config['expire']);

        return true;
    }

    /**
     * 设置过期时间
     */
    public function expire($name = '', $expire = 0)
    {

        $expire = $this->redis->expire($name, $expire);

        if ($expire !== true) exception();

        return true;
    }

    /**
     * 设置过期时间
     */
    public function expirePrefix($name = '', $expire = 0)
    {

        $name = self::name($name);

        $expire = $this->redis->expire($name, $expire);

        if ($expire !== true) exception();

        return true;
    }

    /**
     *  删除
     */
    public function del($name = '')
    {

        $name = self::name($name);

        return $this->redis->del($name);
    }

    /**
     * 读取缓存（哈希、所有）
     */
    public function hGetAll($name = '')
    {

        $name = self::name($name);

        return $this->redis->hGetAll($name);
    }

    /**
     * 设置缓存（字符串）
     */
    public function set($name = '', $value = '', $config = [])
    {

        $name = self::name($name);

        if (is_array($value)) $value = json_encode($value, JSON_UNESCAPED_UNICODE);

        $set = $this->redis->set($name, $value, $config['expire'] ?? null);

        if ($set != true) exception($name . '设置缓存失败');

        return true;
    }

    /**
     * 读取缓存（字符串）
     */
    public function get($name = '', $array = false)
    {

        $name = self::name($name);

        $get = $this->redis->get($name);

        if ($get && $array) $get = json_decode($get, true);

        return $get;
    }

    /**
     * 名称
     */
    public function name($name = '')
    {
        return $this->prefix . $name;
    }

}
